//
//  AssetViewController.m
//  PingTu
//
//  Created by Yangfan on 15/2/4.
//  Copyright (c) 2015年 4gread. All rights reserved.
//

#import "AssetViewController.h"
#import "AssetPickerController.h"

@interface AssetViewController ()

@end

@implementation AssetViewController

- (id)init {
    _indexPathsForSelectedItems=[[NSMutableArray alloc] init];
    
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
    {
        self.tableView.contentInset=UIEdgeInsetsMake(9.0, 2.0, 0, 2.0);
        
        minimumInteritemSpacing=3;
        minimumLineSpacing=3;
        
    }
    else
    {
        self.tableView.contentInset=UIEdgeInsetsMake(9.0, 0, 0, 0);
        
        minimumInteritemSpacing=2;
        minimumLineSpacing=2;
    }
    
    if (self = [super init])
    {
        if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
            [self setEdgesForExtendedLayout:UIRectEdgeNone];
        
        if ([self respondsToSelector:@selector(setContentSizeForViewInPopover:)])
            [self setContentSizeForViewInPopover:kPopoverContentSize];
    }
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    [self setupButtons];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!unFirst) {
        columns=floor(self.view.frame.size.width/(kThumbnailSize.width+minimumInteritemSpacing));
        [self setupAssets];
        unFirst=YES;
    }
    
    if (_backImage != nil) {
        [imageViewBack setImage:_backImage];
    }
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

#pragma mark - Rotation

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
    {
        self.tableView.contentInset=UIEdgeInsetsMake(9.0, 0, 0, 0);
        
        minimumInteritemSpacing=3;
        minimumLineSpacing=3;
    }
    else
    {
        self.tableView.contentInset=UIEdgeInsetsMake(9.0, 0, 0, 0);
        
        minimumInteritemSpacing=2;
        minimumLineSpacing=2;
    }
    
    columns=floor(self.view.frame.size.width/(kThumbnailSize.width+minimumInteritemSpacing));
    
    [self.tableView reloadData];
}

#pragma mark - Setup

- (void)setupViews
{
    
    // 底部的高斯模糊的图片
    imageViewBack = [[UIImageView alloc] init];
    [imageViewBack setFrame:self.view.bounds];
    [imageViewBack setImage:[UIImage imageNamed:@"morenBack.jpg"]];
    [self.view addSubview:imageViewBack];
    
    // 顶部的导航
    UIView *navigationView = [[UIView alloc] init];
    [navigationView setFrame:CGRectMake(0, 0, Kwidth, 44)];
    [navigationView setBackgroundColor:HexRGBAlpha(0x000000, 0.5)];
    [self.view addSubview:navigationView];
    
    UILabel *title = [[UILabel alloc] initWithFrame:navigationView.bounds];
    title.text = @"选择照片";
    [title setTextAlignment:NSTextAlignmentCenter];
    title.textColor = [UIColor whiteColor];
    [navigationView addSubview:title];
    
    UIButton *backToMainButton = [[UIButton alloc] init];
    [backToMainButton setFrame:CGRectMake(0, 0, 63, 44)];
    [backToMainButton setBackgroundImage:[UIImage imageNamed:@"xiangbu"] forState:UIControlStateNormal];
    [backToMainButton setBackgroundImage:[UIImage imageNamed:@"xiangbu"] forState:UIControlStateHighlighted];
    [backToMainButton addTarget:self action:@selector(backToMainButton:) forControlEvents:UIControlEventTouchUpInside];
    [navigationView addSubview:backToMainButton];
    
    UIButton *cancelAndBack = [[UIButton alloc] init];
    [cancelAndBack setFrame:CGRectMake(Kwidth - 80, 0, 63, 44)];
    [cancelAndBack setBackgroundImage:[UIImage imageNamed:@"cancelButton"] forState:UIControlStateNormal];
    [cancelAndBack setBackgroundImage:[UIImage imageNamed:@"cancelButton"] forState:UIControlStateHighlighted];
    [cancelAndBack addTarget:self action:@selector(finishPickingAssets:) forControlEvents:UIControlEventTouchUpInside];
    [navigationView addSubview:cancelAndBack];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, Kwidth, Kheight - 44 - 135) style:UITableViewStylePlain];
    [self.tableView setBackgroundColor:HexRGBAlpha(0xffffff, 0.6)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

- (void)setupButtons
{
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithTitle:@"取消"
                                     style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(finishPickingAssets:)];
}

- (void)setupAssets {
    self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
    self.numberOfPhotos = 0;
    self.numberOfVideos = 0;
    
    if (!self.assets)
        self.assets = [[NSMutableArray alloc] init];
    else
        [self.assets removeAllObjects];
    
    // 供下面的回调使用
    ALAssetsGroupEnumerationResultsBlock resultsBlock = ^(ALAsset *asset, NSUInteger index, BOOL *stop) {
        if (asset) {
            [self.assets addObject:asset];
            NSString *type = [asset valueForProperty:ALAssetPropertyType];
            if ([type isEqual:ALAssetTypePhoto])
                self.numberOfPhotos ++;
            if ([type isEqual:ALAssetTypeVideo])
                self.numberOfVideos ++;
        } else if (self.assets.count > 0) {
            [self.tableView reloadData];
            
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:ceil(self.assets.count*1.0/columns)  inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    };
    
    [self.assetsGroup enumerateAssetsUsingBlock:resultsBlock];
}

#pragma mark - UITableView DataSource
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==ceil(self.assets.count*1.0/columns)) {
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cellFooter"];
        
        if (cell==nil) {
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellFooter"];
            cell.textLabel.font=[UIFont systemFontOfSize:18];
            cell.textLabel.backgroundColor=[UIColor clearColor];
            cell.textLabel.textAlignment=NSTextAlignmentCenter;
            cell.textLabel.textColor=[UIColor blackColor];
            cell.backgroundColor=[UIColor clearColor];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        NSString *title;
        
        if (_numberOfVideos == 0)
            title = [NSString stringWithFormat:NSLocalizedString(@"%ld 张照片", nil), (long)_numberOfPhotos];
        else if (_numberOfPhotos == 0)
            title = [NSString stringWithFormat:NSLocalizedString(@"%ld 部视频", nil), (long)_numberOfVideos];
        else
            title = [NSString stringWithFormat:NSLocalizedString(@"%ld 张照片, %ld 部视频", nil), (long)_numberOfPhotos, (long)_numberOfVideos];
        
        cell.textLabel.text=title;
        return cell;
    }
    
    
    NSMutableArray *tempAssets=[[NSMutableArray alloc] init];
    for (int i=0; i<columns; i++) {
        if ((indexPath.row*columns+i)<self.assets.count) {
            [tempAssets addObject:[self.assets objectAtIndex:indexPath.row*columns+i]];
        }
    }
    
    static NSString *CellIdentifier = kAssetViewCellIdentifier;
    AssetPickerController *picker = (AssetPickerController *)self.navigationController;
    
    AssetViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        cell=[[AssetViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.delegate=self;
    
    [cell bind:tempAssets selectionFilter:picker.selectionFilter minimumInteritemSpacing:minimumInteritemSpacing minimumLineSpacing:minimumLineSpacing columns:columns assetViewX:(self.tableView.frame.size.width-kThumbnailSize.width*tempAssets.count-minimumInteritemSpacing*(tempAssets.count-1))/2];
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return ceil(self.assets.count*1.0/columns)+1;
}

#pragma mark - UITableView Delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==ceil(self.assets.count*1.0/columns)) {
        return 44;
    }
    return kThumbnailSize.height+minimumLineSpacing;
}


#pragma mark - ZYQAssetViewCell Delegate

- (BOOL)shouldSelectAsset:(ALAsset *)asset
{
    AssetPickerController *vc = (AssetPickerController *)self.navigationController;
    BOOL selectable = [vc.selectionFilter evaluateWithObject:asset];
    if (_indexPathsForSelectedItems.count > vc.maximumNumberOfSelection) {
        if (vc.delegate!=nil&&[vc.delegate respondsToSelector:@selector(assetPickerControllerDidMaximum:)]) {
            [vc.delegate assetPickerControllerDidMaximum:vc];
        }
    }
    
    return (selectable && _indexPathsForSelectedItems.count < vc.maximumNumberOfSelection);
}

- (void)didSelectAsset:(ALAsset *)asset
{
    [_indexPathsForSelectedItems addObject:asset];
    
    AssetPickerController *vc = (AssetPickerController *)self.navigationController;
    vc.indexPathsForSelectedItems = _indexPathsForSelectedItems;
    
    if (vc.delegate!=nil&&[vc.delegate respondsToSelector:@selector(assetPickerController:didSelectAsset:)])
        [vc.delegate assetPickerController:vc didSelectAsset:asset];
    [[D_Main_Appdelegate showAllSelectedImageView] addImageWith:asset];
    //    [self setTitleWithSelectedIndexPaths:_indexPathsForSelectedItems];
}

- (void)didDeselectAsset:(ALAsset *)asset
{
    [_indexPathsForSelectedItems removeObject:asset];
    
    AssetPickerController *vc = (AssetPickerController *)self.navigationController;
    vc.indexPathsForSelectedItems = _indexPathsForSelectedItems;
    
    if (vc.delegate!=nil&&[vc.delegate respondsToSelector:@selector(assetPickerController:didDeselectAsset:)])
        [vc.delegate assetPickerController:vc didDeselectAsset:asset];
    [[D_Main_Appdelegate showAllSelectedImageView] deletePintuAction:asset];
    //    [self setTitleWithSelectedIndexPaths:_indexPathsForSelectedItems];
    
    
    
}





#pragma mark - Title

- (void)setTitleWithSelectedIndexPaths:(NSArray *)indexPaths
{
    // Reset title to group name
    if (indexPaths.count == 0)
    {
        self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
        return;
    }
    
    BOOL photosSelected = NO;
    BOOL videoSelected  = NO;
    
    for (int i=0; i<indexPaths.count; i++) {
        ALAsset *asset = indexPaths[i];
        
        if ([[asset valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypePhoto])
            photosSelected  = YES;
        
        if ([[asset valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
            videoSelected   = YES;
        
        if (photosSelected && videoSelected)
            break;
        
    }
    
    NSString *format;
    
    if (photosSelected && videoSelected)
        format = NSLocalizedString(@"已选择 %ld 个项目", nil);
    
    else if (photosSelected)
        format = (indexPaths.count > 1) ? NSLocalizedString(@"已选择 %ld 张照片", nil) : NSLocalizedString(@"已选择 %ld 张照片 ", nil);
    
    else if (videoSelected)
        format = (indexPaths.count > 1) ? NSLocalizedString(@"已选择 %ld 部视频", nil) : NSLocalizedString(@"已选择 %ld 部视频 ", nil);
    
    self.title = [NSString stringWithFormat:format, (long)indexPaths.count];
}


#pragma mark - Actions
- (void)backToMainButton:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)finishPickingAssets:(id)sender {
    [D_Main_Appdelegate hiddenPreView];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //    ZYQAssetPickerController *picker = (ZYQAssetPickerController *)self.navigationController;
    //
    //    if (_indexPathsForSelectedItems.count < picker.minimumNumberOfSelection) {
    //        if (picker.delegate!=nil&&[picker.delegate respondsToSelector:@selector(assetPickerControllerDidMaximum:)]) {
    //            [picker.delegate assetPickerControllerDidMaximum:picker];
    //        }
    //    }
    //
    //
    //    if ([picker.delegate respondsToSelector:@selector(assetPickerController:didFinishPickingAssets:)])
    //        [picker.delegate assetPickerController:picker didFinishPickingAssets:_indexPathsForSelectedItems];
    //
    //    if (picker.isFinishDismissViewController) {
    //        [picker.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
    //    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end